package com.yxsd.common.utils;

import it.sauronsoftware.base64.Base64;

import java.io.*;

/**
 * Base64Utils
 *
 * @author: zhangteng
 * @time: 2015/6/17 14:32
 */
public class Base64Utils {

    // 文件读取缓冲区大小
    private final static int FILE_CACHE_SIZE = 1024;

    /**
     * Base64字符串解码为二进制数据
     *
     * @param base64
     * @return
     * @throws Exception
     */
    public static byte[] decode(String base64) throws Exception {
        return Base64.decode(base64.getBytes());
    }

    /**
     * 二进制数据编码为Base64字符串
     *
     * @param bytes
     * @return
     * @throws Exception
     */
    public static String encode(byte[] bytes) throws Exception {
        return new String(Base64.encode(bytes));
    }

    /**
     * 将文件编码为Base64字符串
     *
     * @param filePath  文件绝对路径
     * @return
     * @throws Exception
     */
    public static String encodeFile(String filePath) throws Exception {
        byte[] bytes = fileToByte(filePath);
        return encode(bytes);
    }

    /**
     * Base64字符串解码写回文件
     *
     * @param filePath  文件绝对路径
     * @param base64    base64字符串
     * @throws Exception
     */
    public static void decodeToFile(String filePath, String base64) throws Exception {
        byte[] bytes = decode(base64);
        byteArrayToFile(filePath, bytes);
    }

    /**
     * 文件转换为二进制数组
     *
     * @param filePath
     * @return
     * @throws Exception
     */
    public static byte[] fileToByte(String filePath) throws Exception {
        byte[] data = null;
        File file = new File(filePath);
        if (file.exists()) {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);
            byte[] cache = new byte[FILE_CACHE_SIZE];
            int len = 0;
            while((len = bis.read(cache)) != -1) {
                baos.write(cache, 0 , len);
                baos.flush();
            }
            baos.close();
            bis.close();
            data = baos.toByteArray();
        }
        return data;
    }

    public static void byteArrayToFile(String filePath, byte[] bytes) throws Exception {
        InputStream is = new ByteArrayInputStream(bytes);
        File destFile = new File(filePath);
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }
        destFile.createNewFile();
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
        byte[] cache = new byte[FILE_CACHE_SIZE];
        int len = 0;
        while ((len = is.read(cache)) != -1) {
            bos.write(cache, 0, len);
            bos.flush();
        }
        bos.close();
        is.close();
    }
}
